package ai.people.core.redis.redisson;

import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.exception.type.BusinessException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author LiGuanNan
 * @date 2022/6/7 11:09
 */
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonAutoConfiguration {
    @Autowired
    RedisProperties redisProperties;

    @Bean(destroyMethod="shutdown")
    @ConditionalOnProperty(prefix = "spring.redis", value = "mode", havingValue = "single")
    @ConditionalOnMissingBean(value = {RedissonClient.class})
    @DependsOn(value = "redisConnectionFactory")
    RedissonClient singleRedisson() throws IOException {
        Config config = new Config();
        config.setTransportMode(TransportMode.NIO);
        StringBuilder redisAr = new StringBuilder("redis://");
        redisAr.append(redisProperties.getHost()).append(":").append(redisProperties.getPort());
        config.useSingleServer().setAddress(redisAr.toString());
        return Redisson.create(config);
    }

    @Bean(destroyMethod="shutdown")
    @ConditionalOnProperty(prefix = "spring.redis", value = "mode", havingValue = "sentinel")
    @ConditionalOnMissingBean(value = {RedissonClient.class})
    @DependsOn(value = "redisConnectionFactory")
    RedissonClient sentinelRedisson() throws IOException {
        Config config = new Config();
        config.setTransportMode(TransportMode.NIO);
        if((redisProperties.getSentinel() != null && !CollectionUtils.isEmpty(redisProperties.getSentinel().getNodes()))){
            List<String> sentinelArs = redisProperties.getSentinel().getNodes();
            for (int i = 0; i < sentinelArs.size(); i++) {
                sentinelArs.set(i, "redis://" + sentinelArs.get(i));
            }
            config.useSentinelServers().addSentinelAddress(sentinelArs.toArray(String[]::new)).setMasterName(redisProperties.getSentinel().getMaster());
            return Redisson.create(config);
        }
        throw new BusinessException(CommonEnum.CONFIGURATION_ERROR);
    }


}
